<template>
    <div class="min-h-screen bg-gray-100 text-gray-900 flex justify-center">
        <div class="max-w-screen-xl m-0 sm:m-10 bg-white shadow sm:rounded-lg flex justify-center flex-1">
            <div class="flex-1 bg-indigo-100 text-center hidden lg:flex relative">
                <div class="m-12 xl:m-16 w-full bg-contain bg-center bg-no-repeat"
                    style="background-image: url('../../../public/authBg.svg');">
                </div>
                <el-button color="#626aef" class="flex items-center gap-2 absolute left-1 top-2" @click="handleToBack">
                    <el-icon>
                        <Back />
                    </el-icon>
                    <span class="text-xs">
                        返回
                    </span>
                </el-button>
            </div>
            <div class="lg:w-1/2 xl:w-5/12 p-6 sm:p-12">
                <div class="">
                    <img src="../../../public/logo.png" class="w-32 mx-auto" />

                </div>
                <div class="mt-12 flex flex-col items-center">
                    <h1 class="text-2xl xl:text-3xl font-extrabold">
                        {{ isAdmin ? '后台管理系统 —— ' : '' }}会员{{ name }}
                    </h1>
                    <div class="w-full flex-1 mt-8">
                        <div class="flex flex-col items-center" v-show="!isRegister">
                            <button
                                class="w-full max-w-xs font-bold shadow-sm rounded-lg py-3 bg-indigo-100 text-gray-800 flex items-center justify-center transition-all duration-300 ease-in-out focus:outline-none hover:shadow focus:shadow-sm focus:shadow-outline">
                                <div class="bg-white p-2 rounded-full">
                                    <svg class="w-4" viewBox="0 0 533.5 544.3">
                                        <path
                                            d="M533.5 278.4c0-18.5-1.5-37.1-4.7-55.3H272.1v104.8h147c-6.1 33.8-25.7 63.7-54.4 82.7v68h87.7c51.5-47.4 81.1-117.4 81.1-200.2z"
                                            fill="#4285f4" />
                                        <path
                                            d="M272.1 544.3c73.4 0 135.3-24.1 180.4-65.7l-87.7-68c-24.4 16.6-55.9 26-92.6 26-71 0-131.2-47.9-152.8-112.3H28.9v70.1c46.2 91.9 140.3 149.9 243.2 149.9z"
                                            fill="#34a853" />
                                        <path
                                            d="M119.3 324.3c-11.4-33.8-11.4-70.4 0-104.2V150H28.9c-38.6 76.9-38.6 167.5 0 244.4l90.4-70.1z"
                                            fill="#fbbc04" />
                                        <path
                                            d="M272.1 107.7c38.8-.6 76.3 14 104.4 40.8l77.7-77.7C405 24.6 339.7-.8 272.1 0 169.2 0 75.1 58 28.9 150l90.4 70.1c21.5-64.5 81.8-112.4 152.8-112.4z"
                                            fill="#ea4335" />
                                    </svg>
                                </div>
                                <span class="ml-4">
                                    微信登录
                                </span>
                            </button>
                        </div>
                        <div class="my-12 border-b text-center">
                            <div
                                class="leading-none px-2 inline-block text-sm text-gray-600 tracking-wide font-medium bg-white transform translate-y-1/2">
                                使用邮箱或者短信{{ name }}
                            </div>
                        </div>

                        <div class="mx-auto max-w-xs">
                            <el-form ref="ruleFormRef" :model="form" :rules="rulesComputed">
                                <el-form-item prop="name">
                                    <el-input class="h-14" v-model="form.name" placeholder="请输入邮箱或者电话" />
                                </el-form-item>
                                <el-form-item prop="password" class="mt-5">
                                    <el-input class="h-14" type="password" v-model="form.password"
                                        placeholder="请输入密码" />
                                </el-form-item>
                                <el-form-item prop="check_password" class="mt-5" v-if="isRegister">
                                    <el-input class="h-14" type="password" v-model="form.check_password"
                                        placeholder="请确认密码" />
                                </el-form-item>
                                <el-form-item>
                                    <el-button size="large"
                                        class="mt-5 tracking-wide font-semibold h-7 bg-indigo-500 text-gray-100 w-full py-4 rounded-lg hover:bg-indigo-700 transition-all duration-300 ease-in-out flex items-center justify-center focus:shadow-outline focus:outline-none"
                                        type="primary" @click="submitForm(ruleFormRef)" color="#6366f1">
                                        <div class="flex justify-center items-center gap-2">
                                            <svg class="w-6 h-6 -ml-2" fill="none" stroke="currentColor"
                                                stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                                                <path d="M16 21v-2a4 4 0 00-4-4H5a4 4 0 00-4 4v2" />
                                                <circle cx="8.5" cy="7" r="4" />
                                                <path d="M20 8v6M23 11h-6" />
                                            </svg>
                                            <span>
                                                {{ name }}
                                            </span>
                                        </div>
                                    </el-button>
                                </el-form-item>
                            </el-form>
                            <p class="mt-6 text-xs text-gray-600 text-center">
                                我同意遵守HtmlCode平台的
                                <a href="#" class="border-b border-gray-500 border-dotted">
                                    服务条款
                                </a>
                                和
                                <a href="#" class="border-b border-gray-500 border-dotted">
                                    隐私政策
                                </a>
                            </p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { reactive, ref, computed } from 'vue';
import { ElMessage, type FormInstance } from 'element-plus';
import { useRouter } from 'vue-router';
import { http } from '../../axios';
import { storage } from '../../utils/storage';
import { useUserStore } from '../../store/useUserStore';

type TProps = {
    name?: string
    isRegister?: boolean
    isAdmin?: boolean // 是否是后台管理系统的登录页面
}

const { name = '登录', isRegister = false, isAdmin = false } = defineProps<TProps>();
const router = useRouter();
const { handleSetUser } = useUserStore();

const ruleFormRef = ref<FormInstance>();
const form = reactive<TAuthForm>({
    name: '1123654054@11.com',
    password: '123123123',
    check_password: ''
});

const validateAccount = (_: any, value: any, callback: any) => { // 自定义验证规则
    if (value === '') {
        callback(new Error('请输入邮箱或者电话'))
    } else {
        if (!isValidEmailOrPhone(value)) {
            callback(new Error('格式错误'));
        }
        callback()
    }
}

const validateCheckPassword = (_: any, value: any, callback: any) => { // 验证确认密码
    if (value === '') {
        callback(new Error('请输入确认密码'))
    } else {
        if (form.password !== form.check_password) {
            callback(new Error('密码输入不一致'));
        }
        callback()
    }
}

function isValidEmailOrPhone(value: string) {
    const combinedRegex = /^(?:[^\s@]+@[^\s@]+\.[^\s@]+|1[3-9]\d{9})$/;
    return combinedRegex.test(value);
}

const rules = reactive<TAuthFormRules>({
    name: [{ validator: validateAccount, trigger: 'blur' }],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, max: 30, message: '密码长度6-30位之间', trigger: 'blur' }
    ],
    check_password: [{ validator: validateCheckPassword, trigger: 'blur' }],
});

const rulesComputed = computed(() => {
    const baseRules = { ...rules };
    if (!isRegister) {
        delete baseRules['check_password']
    }
    return baseRules;

});

const submitForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.validate((valid) => {
        if (valid) {
            handleSubmitHttp(form);
        } else {
            console.log('error submit!')
        }
    });
};

const handleSubmitHttp = async (val: TAuthForm) => {
    let url: string = '';
    switch (isRegister) {
        case true:
            url = 'auth/register';
            break;
        case false:
            url = 'auth/login';
            delete val['check_password'];
            break;
        default:
            url = ''
    }
    const { data, message } = await http.request<TUser>({
        url,
        method: 'POST',
        data: val
    });

    ElMessage({
        message,
        type: 'success',
        plain: true,
    });

    if (!isRegister) {
        // 登录成功设置缓存
        storage.set('token', data.token!, 3600);
        handleSetUser(data); // 设置全局状态用户信息
        if (isAdmin) {
            router.push({
                name: 'adminHome'
            });
            return;
        }
        router.push('/');

    } else {
        // 注册
        router.push('/auth/login');
    }
}

const handleToBack = () => {
    // 返回上一页
    router.back();
}

</script>

<style scoped></style>